package se.peterbjorkman.android.trafikkamera;

import se.peterbjorkman.android.trafikkamera.providers.CameraContentProvider;
import se.peterbjorkman.android.trafikkamera.providers.CameraDefs;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class SelectRouteActivity extends ListActivity {
	
	public static final String SELECTEDID = "SelectedId";
	public static final String EXTRA_ID   = "Id";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main); // TODO Layout

		String[] displayFields = new String[] { CameraDefs.NAME}; // TODO CameraDefs

		int[] displayViews = new int[] { android.R.id.text1 };

		long id = getIntent().getLongExtra(EXTRA_ID, 0);
		
		Cursor cur = getCountyCursor(id, this);
		
		setListAdapter(new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, cur, displayFields,
				displayViews));
	}

	private static Cursor getCountyCursor(long cameraId, Activity owningActivity) {
		String[] projection = new String[] { 
				CameraDefs.ID, 
				CameraDefs.NAME}; //TODO Cameradef
		
		String filter = null;
		if (cameraId != 0)
			filter = "NOT EXISTS (SELECT 1 from camerasinroutes cir where cir.routeid = routes._id AND cir.cameraId = " + cameraId + ")";

		Cursor cur = owningActivity.managedQuery(
				CameraContentProvider.ROUTES_URI,
				projection, filter, null, CameraDefs.NAME);
		return cur;
	}
	
	public static boolean shouldBeShown(long cameraId, Activity owningActivity) {
		return getCountyCursor(cameraId, owningActivity).moveToFirst();
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = getIntent();
		intent.putExtra(SELECTEDID, id);
		setResult(RESULT_OK, intent);
		finish();
	}
}
